#include "firstwidget.h"
#include "ui_firstwidget.h"

firstWidget::firstWidget(QWidget *parent)
    : QWidget(parent), ui(new Ui::firstWidget)
{
    ui->setupUi(this);

    QString expName = "listing" + QDateTime::currentDateTime()
                      .toString("MMddyyyyhhmm") + ".txt";
    ui->lineEdit->setText( getTargetFolder() + expName );
}

void firstWidget::on_htmlRButton_clicked()
{
    ui->lineEdit->setText( ui->lineEdit->text()
                           .left( ui->lineEdit->text().lastIndexOf('.') ) + ".html" );
}

void firstWidget::on_xmlRButton_clicked()
{
    ui->lineEdit->setText( ui->lineEdit->text()
                           .left( ui->lineEdit->text().lastIndexOf('.') ) + ".xml" );
}

void firstWidget::on_csvRButton_clicked()
{
    ui->lineEdit->setText( ui->lineEdit->text()
                           .left( ui->lineEdit->text().lastIndexOf('.') ) + ".csv" );
}

void firstWidget::on_txtRButton_clicked()
{
    ui->lineEdit->setText( ui->lineEdit->text()
                           .left( ui->lineEdit->text().lastIndexOf('.') ) + ".txt" );
}

void firstWidget::on_toolButton_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Export file"),
                                                    ui->lineEdit->text(),
                                                    tr("Text files (*.txt);;CSV files (*.csv);;XML files (*.xml);;HTML files (*.html)"));

    if ( !fileName.isEmpty() )
    {
        ui->lineEdit->setText( fileName );
        setTargetFolder();
    }
}

firstWidget::~firstWidget()
{
    delete ui;
}

void firstWidget::setTargetFolder()
{
    ui->lineEdit->setText( ui->lineEdit->text().replace( "\\", "/" ) );

    QSettings settings("File-folder listing", "Settings");
    settings.beginGroup("Folders");
    settings.setValue("export_folder", ui->lineEdit->text()
                           .left( ui->lineEdit->text().lastIndexOf('/') ) );
    settings.endGroup();
}

QString firstWidget::getTargetFolder()
{
    QString retStr;

    QSettings settings("File-folder listing", "Settings");
    settings.beginGroup("Folders");
        retStr = settings.value("export_folder", "" ).toString();
    settings.endGroup();

    if ( retStr.isEmpty() )
        retStr = qApp->applicationDirPath() + "/";
    return retStr;
}

int firstWidget::getSelectedMode()
{
    if ( ui->txtRButton->isChecked() )
        return 0;
    else if ( ui->csvRButton->isChecked() )
        return 1;
    else if ( ui->xmlRButton->isChecked() )
        return 2;
    //else if ( ui->htmlRButton->isChecked() )
    //    return 3;

    return -1;
}

QString firstWidget::getFileName()
{
    return ui->lineEdit->text();
}
